﻿using CommunityToolkit.Mvvm.ComponentModel;
using ContactSMS.Client.Models;
using ContactSMS.Client.Service;
using System.Collections.ObjectModel;

namespace ContactSMS.Client.ViewModels
{
    public partial class MessageDetailViewModel : ObservableObject
    {
        private readonly MessageService messageService;
        [ObservableProperty]
        public ObservableCollection<MessageDetailModel> messages = new ObservableCollection<MessageDetailModel>();

        [ObservableProperty]
        private ObservableCollection<MessageNewModel> messageList = new ObservableCollection<MessageNewModel>();

        public MessageDetailViewModel(MessageService messageService)
        {
            //this.LoadMessages();
            //System.Diagnostics.Debug.WriteLine($"Messages count: {Messages.Count}");
            this.messageService = messageService;
        }

        public async Task LoadMessage(long id, int page = 1, int pageSize = 15)
        {
            try
            {
                var result = await messageService.GetMessageAsync(id, page, pageSize);
                if (result != null && result.Success)
                {
                    MessageList = new ObservableCollection<MessageNewModel>(result.Data.List);
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", result?.Message ?? "Failed to load contacts", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }

        private void LoadMessages()
        {
            long[] DateArr = new long[]{
                1724373248,
                1724376848,
                1724377448,
                1724377448,
                1724377448,
                1724463848,
                1724463848,
                1724464448,
                1724464448,
                1724464448,
                1724486048,
                1724486048,
                1724486048,
                1724546048,
                1724574848
            };
            for (int i = 0; i < 15; i++)
            {
                long id = i + 1;
                long UserId = i % 2 == 0 ? 0 : 1;
                var message = new MessageDetailModel()
                {
                    Id = id,
                    UserId = UserId,
                    Content = "11111111111111111消息内容2222222222222222222222222222222222222222222222222222222222222222222222222222222222222" + id,
                    Date = DateArr[i]
                };
                Messages.Add(message);
            }
        }
    }
}
